package com.party.admin.biz.serviceOrder;

import com.google.common.collect.Maps;
import com.party.common.redis.StringJedis;
import com.party.common.utils.DateUtils;
import com.party.core.model.charge.PackageMember;
import com.party.core.model.charge.ProductPackage;
import com.party.core.model.member.MemberGroupInfo;
import com.party.core.model.partner.MemberPartner;
import com.party.core.model.system.MemberSysRole;
import com.party.core.model.system.RoleEnum;
import com.party.core.model.system.RoleType;
import com.party.core.model.system.SysRole;
import com.party.core.service.charge.IPackageMemberService;
import com.party.core.service.charge.IPackageService;
import com.party.core.service.member.IMemberGroupInfoService;
import com.party.core.service.partner.IMemberPartnerService;
import com.party.core.service.partner.biz.MemberPartnerBizService;
import com.party.core.service.system.IMemberSysRoleService;
import com.party.core.service.system.ISysRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @program: party
 * @description: “服务订购”业务服务
 * @author: Hua Qunhao
 * @create: 2019-05-24 12:40
 **/
@Service
public class ServiceOrderBizService {

    protected static Logger logger = LoggerFactory.getLogger(ServiceOrderBizService.class);

    @Autowired
    private IPackageMemberService packageMemberService;

    @Autowired
    private IMemberPartnerService memberPartnerService;

    @Autowired
    private IMemberGroupInfoService memberGroupInfoService;

    @Autowired
    private IPackageService packageService;

    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private IMemberSysRoleService memberSysRoleService;
    @Autowired
    private MemberPartnerBizService memberPartnerBizService;

    @Autowired
    private StringJedis stringJedis;

    public boolean isUnpaidOrder(String memberId) {
        return packageMemberService.isUnpaidOrder(memberId);
    }

    public void updateSystemRelated(String packageMemberId) {

        PackageMember packageMember = packageMemberService.get(packageMemberId);
        MemberPartner mpOrg = memberPartnerService.findByMemberId(packageMember.getMemberId());
        MemberGroupInfo memberGroupInfo = memberGroupInfoService.findByMemberId(packageMember.getMemberId());
        ProductPackage productPackage = packageService.get(packageMember.getLevelId());

        logger.info("系统购买审核————初始值 ——packageMember" + packageMember);
        logger.info("系统购买审核————初始值 ——MemberPartner" + mpOrg);
        logger.info("系统购买审核————初始值 ——memberGroupInfo" + memberGroupInfo);

        packageMember.setAuditStatus(PackageMember.AUDIT_STATUS_SUCCEED); // 更改审核状态


        if (null == mpOrg.getSystemType() || 0 == mpOrg.getSystemType()) { // 第一次购买

            //设置当前系统类型
            mpOrg.setSystemType(productPackage.getSystemType());
            String roleCode = "";

            //分配系统套餐角色-----众筹系统
            if (ProductPackage.SYSTEM_TYPE_ZC == productPackage.getSystemType()) {
                roleCode = RoleEnum.PARTNER_2_ROLE.getCode();
            }
            //分配系统套餐角色-----社群系统
            if (ProductPackage.SYSTEM_TYPE_SQ == productPackage.getSystemType()) {
                roleCode = RoleEnum.COMMUNITY__ROLE.getCode();
            }

            Integer roleType = RoleType.PARTNER_ROLE.getCode();
            SysRole sysRole = sysRoleService.getRole(roleCode, roleType);

            MemberSysRole memberSysRole = new MemberSysRole(packageMember.getMemberId(), sysRole.getId());
            memberSysRoleService.insert(memberSysRole);

            //处理系统到期时间
            memberGroupInfo.setExpirationTime(packageMember.getEndTime());
        } else {

            if (DateUtils.compareDate(memberGroupInfo.getExpirationTime(), new Date()) == 1) {  //未到期

                if (productPackage.getSystemType() == mpOrg.getSystemType()) {  //续费

                    List<PackageMember> packageMemberList = packageMemberService.getLatelyPaySuccess(mpOrg.getMemberId());
                    if (packageMemberList.size() < 1) {
                        //admin 添加的客户
                        //累加后的到期时间
                        Date newEndDate = DateUtils.addMonth(memberGroupInfo.getExpirationTime(),
                                DateUtils.getMonth(packageMember.getStartTime(), packageMember.getEndTime()));

                        memberGroupInfo.setExpirationTime(newEndDate);
                    } else {
                        //累加后的到期时间
                        memberGroupInfo.setExpirationTime(packageMember.getEndTime());
                    }
                } else if (ProductPackage.SYSTEM_TYPE_SQ == mpOrg.getSystemType()
                        && ProductPackage.SYSTEM_TYPE_ZC == productPackage.getSystemType()) {  //升级

                    //分配系统套餐角色-----众筹系统
                    SysRole sysRole = sysRoleService.getRole(RoleEnum.PARTNER_2_ROLE.getCode(),
                            RoleType.PARTNER_ROLE.getCode());
                    MemberSysRole memberSysRole = new MemberSysRole(packageMember.getMemberId(), sysRole.getId());
                    memberSysRoleService.insert(memberSysRole);

                    //累加后的到期时间
/*                            Date newEndDate = DateUtils.addMonth(new Date(),
                                    DateUtils.getMonth(packageMember.getStartTime(), packageMember.getEndTime()));

                            memberGroupInfo.setExpirationTime(newEndDate);*/

                    //设置当前系统类型
                    mpOrg.setSystemType(productPackage.getSystemType());
                }
            } else { //已到期

                if (productPackage.getSystemType() == mpOrg.getSystemType()) { //续费
                    //累加后的到期时间
                    Date newEndDate = DateUtils.addMonth(new Date(),
                            DateUtils.getMonth(packageMember.getStartTime(), packageMember.getEndTime()));

                    memberGroupInfo.setExpirationTime(newEndDate);
                } else {
                    if (ProductPackage.SYSTEM_TYPE_SQ == mpOrg.getSystemType()
                            && ProductPackage.SYSTEM_TYPE_ZC == productPackage.getSystemType()) { //升级

                        //分配系统套餐角色-----众筹系统
                        SysRole sysRole = sysRoleService.getRole(RoleEnum.PARTNER_2_ROLE.getCode(),
                                RoleType.PARTNER_ROLE.getCode());
                        MemberSysRole memberSysRole = new MemberSysRole(packageMember.getMemberId(), sysRole.getId());
                        memberSysRoleService.insert(memberSysRole);

                    } else if (ProductPackage.SYSTEM_TYPE_ZC == mpOrg.getSystemType()
                            && ProductPackage.SYSTEM_TYPE_SQ == productPackage.getSystemType()) { //降级
                        //删除该用户所有的套餐角色，重新分配一个社群角色

                        //注：因系统到期时间是和用户一对一关联的，没有和套餐角色关联,
                        // 故删除其他角色后将失去原来的功能菜单，只有当前的社群角色功能菜单
                        HashMap<String, Object> mmp = Maps.newHashMap();
                        mmp.put("memberId", packageMember.getMemberId());
                        List<MemberSysRole> memberSysRoles = memberSysRoleService.queryMemberRoleAll(RoleType.PARTNER_ROLE.getCode(), mmp);
                        for (MemberSysRole msr : memberSysRoles) {
                            logger.info("降级刪除的角色 ：" + msr);
                            memberSysRoleService.deleteByRoleIdAndMemberId(msr.getRoleId(), msr.getMemberId());
                        }
                        SysRole sysRole = sysRoleService.getRole(RoleEnum.COMMUNITY__ROLE.getCode(),
                                RoleType.PARTNER_ROLE.getCode());
                        MemberSysRole memberSysRole = new MemberSysRole(packageMember.getMemberId(), sysRole.getId());
                        memberSysRoleService.insert(memberSysRole);
                    }
                    //累加后的到期时间
                    Date newEndDate = DateUtils.addMonth(new Date(),
                            DateUtils.getMonth(packageMember.getStartTime(), packageMember.getEndTime()));

                    memberGroupInfo.setExpirationTime(newEndDate);
                    //设置当前系统类型
                    mpOrg.setSystemType(productPackage.getSystemType());
                }
            }
        }

        packageMemberService.update(packageMember);
        memberPartnerService.update(mpOrg);

        memberPartnerBizService.saveOrUpdateChildMemberPartner(mpOrg);

        memberGroupInfoService.update(memberGroupInfo);

        try {
            String key = "EXPIRE_DATE_" + mpOrg.getMemberId();
            stringJedis.setValue(key, DateUtils.formatDate(memberGroupInfo.getExpirationTime(), "yyyy-MM-dd HH:mm:ss"));
            logger.info("系统购买审核————log8");
        } catch (Exception e) {
            logger.error("redis 设置 key--{}过期时间异常", "EXPIRE_DATE_" + mpOrg.getMemberId(), e);
        }

        logger.info("系统购买审核————修改后的值 ——packageMember" + packageMember);
        logger.info("系统购买审核————修改后的值 ——MemberPartner" + mpOrg);
        logger.info("系统购买审核————修改后的值 ——memberGroupInfo" + memberGroupInfo);
    }
}
